import React, { useCallback, useState, useEffect } from 'react'
import {
  Form,
  Input,
  Button,
  Radio,
  DatePicker,
  Select,
  Space,
  Upload,
  Switch,
  Cascader,
  message as Message,
} from 'antd'
import {
  PlusOutlined,
} from '@ant-design/icons'
import qs from 'qs'
import moment from 'moment'
import { getDepartments } from '@/api/department'
import { getDistricts } from '@/api/district'
import { getJobs } from '@/api/job'
import { getTags } from '@/api/tag'
import { addDoctor, getDoctorById, updateDoctor } from '@/api/doctor'

import './edit.less'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

// 编辑医生信息
export default function DoctorEdit({location, history}) {
  const [doctorForm] = Form.useForm()

  // 保存照片图像
  const [imageUrl, setImageUrl] = useState('')
  // 科室、院区、职称、标签
  const [departments, setDepartments] = useState([])
  const [districts, setDistricts] = useState([])
  const [jobs, setJobs] = useState([])
  const [tags, setTags] = useState([])
  // 当前页面是修改还是添加的类型 create - 添加   update - 修改
  const [actionType, setActionType] = useState('create')

  // 保存医生信息
  const onSaveDoctor = useCallback(async doctor => {
    // 处理表单获取到的数据
    doctor.birthday = doctor.birthday?.format('YYYY-MM-DD')
    doctor.departmentId = doctor.departmentId?.pop()
    doctor.status = Number(doctor.status)
    doctor.tags = doctor.tags.join(',')
    // 将医生数据包装为 FormData 格式的数据
    const formData = new FormData()
    Object.keys(doctor).forEach(key => {
      formData.append(key, doctor[key])
    })
    // 判断是新增还是修改
    if (actionType === 'create') {
      // 发送网络请求，添加新医生信息
      await addDoctor(formData)
    } else {
      await updateDoctor(formData)
    }
    Message.success('操作成功')
    history.push('/hospital/doctor')
  }, [actionType])

  // 将事件值转换为表单元素值所使用到的方法
  const normFile = useCallback(e => {
    // 将当前选择的文件转换为 base64 格式
    getBase64(e.file, imageUrl => setImageUrl(imageUrl))

    if (Array.isArray(e)) {
      return e
    }

    return e && e.file
  }, [])

  // 组件挂载后，加载科室、院区、职称、标签
  useEffect(async() => {
    // const dep = await getDepartments()
    // console.log('1')
    // const dis = await getDistricts()
    // console.log(2)
    // const jobs = await getJobs()
    // console.log(3)
    // const tags = await getTags()
    // console.log(4)
    // const result = await Promise.allSettled([
    //   getDepartments(),
    //   getDistricts(),
    //   getJobs(),
    //   getTags(),
    // ])
    // console.log(result)
    const [dep, dis, jobs, tags] = await Promise.all([
      getDepartments(),
      getDistricts(),
      getJobs(),
      getTags(),
    ])
    setDepartments(dep.list)
    setDistricts(dis.list)
    setJobs(jobs.list)
    setTags(tags.list)
  }, [])

  // 获取请求页面时的参数数据，如果有传递 id 则是修改，否则是新增
  useEffect(async() => {
    // 从请求参数中获取 id
    const {search} = location
    const {id} = qs.parse(search, { ignoreQueryPrefix: true })
    // 如果存在 id，则当前页面组件是进行修改操作，
    // 需要根据id查询出医生数据回显到表单中
    if (id) {
      // 设置当前页面为修改的类型
      setActionType('update')
      // 查询数据
      const doctor = await getDoctorById(id)
      console.log('医生：', doctor)
      // 将数据进行处理，以回显到表单中
      doctor.birthday = moment(doctor.birthday)
      doctor.departmentId = doctor.department && [doctor.department.pid, doctor.department.id]
      doctor.districtId = doctor.district?.id
      doctor.jobId = doctor.job?.id
      doctor.tags = doctor.tags?.split(',')
      setImageUrl(doctor.avatarUrl)
      doctorForm.setFieldsValue(doctor)
    }
  }, [])

  return (
    <div className="doctor-edit">
      {/* 标题 */}
      <div className="title">编辑医生信息</div>
      {/* 表单 */}
      <Form
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 8,
        }}
        initialValues={{
          password: '123456',
          sex: '男',
          status: true,
        }}
        onFinish={onSaveDoctor}
        className="doctor-form"
        form={doctorForm}
      >
        <Form.Item name="id" hidden><Input /></Form.Item>
        <Form.Item
          name="avatar"
          label="照片"
          valuePropName="file"
          getValueFromEvent={normFile}
        >
          <Upload
            listType="picture-card"
            showUploadList={false}
            beforeUpload={() => false}
          >
            {
              imageUrl
                ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                : (
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>选择照片</div>
                  </div>
                )
            }
          </Upload>
        </Form.Item>
        <Form.Item
          label="医生姓名"
          name="name"
          rules={[
            {
              required: true,
              message: '姓名必填',
            },
          ]}
        >
          <Input placeholder="请输入医生姓名" />
        </Form.Item>
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true,
              message: '用户名必填',
            },
          ]}
        >
          <Input disabled={actionType === 'update'} placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: '密码必填',
            },
          ]}
          hidden={actionType === 'update'}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
        <Form.Item name="sex" label="性别">
          <Radio.Group>
            <Radio value="男">男</Radio>
            <Radio value="女">女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="birthday" label="出生日期">
          <DatePicker placeholder="请选择出生日期" />
        </Form.Item>
        <Form.Item name="districtId" label="院区">
          <Select placeholder="请选择院区">
            {
              districts.map(district => (
                <Select.Option key={district.id} value={district.id}>{district.name}</Select.Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item name="departmentId" label="科室">
          <Cascader
            placeholder="请选择科室"
            options={departments}
            fieldNames={{
              label: 'name',
              value: 'id',
            }}
          ></Cascader>
        </Form.Item>
        <Form.Item name="jobId" label="职称">
          <Select placeholder="请选择职称">
            {
              jobs.map(job => (
                <Select.Option key={job.id} value={job.id}>{job.name}</Select.Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item name="tags" label="医生标签">
          <Select mode="multiple" placeholder="请选择标签">
            {
              tags.map((tag, index) => (
                <Select.Option key={index} value={tag}>{tag}</Select.Option>
              ))
            }
          </Select>
        </Form.Item>
        <Form.Item name="phone" label="电话">
          <Input placeholder="请输入电话号码" />
        </Form.Item>
        <Form.Item name="address" label="地址">
          <Input placeholder="请输入详细通信地址" />
        </Form.Item>
        <Form.Item name="introduction" label="个人简介">
          <Input.TextArea placeholder="请输入个人简介" />
        </Form.Item>
        <Form.Item name="status" label="状态" valuePropName="checked">
          <Switch />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 4,
            span: 8,
          }}
        >
          <Space>
            <Button type="primary" htmlType="submit">保存</Button>
            <Button>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}
